package com.kevin.config;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

/**
 * <p>
 *     用于websocket接收客户端消息时，对消息进行拦截处理
 * </p>
 *
 * @author kevin
 * @create 2018-09-05 18:50
 **/
public class WebSocketClientInterceptor implements ChannelInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketClientInterceptor.class);

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel messageChannel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            logger.info("打开websocket连接：{}",JSON.toJSONString(accessor));
        }

        /**
         * 根据订阅频道获取登录用户ID
         * 频道格式/topic/monitor-{empId}
         */
        if(StompCommand.SUBSCRIBE.equals(accessor.getCommand())){
            logger.info("订阅TOPIC：" + accessor.getDestination() + ",SESSIONID:" + accessor.getSessionId());
        }

        if(StompCommand.DISCONNECT.equals(accessor.getCommand())){
            String sessionId = accessor.getSessionId();
            logger.info("关闭websocket连接：{}",JSON.toJSONString(accessor));
        }
        return message;
    }

    @Override
    public void postSend(Message<?> message, MessageChannel messageChannel, boolean b) {
    }

    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel messageChannel, boolean b, Exception e) {
    }

    @Override
    public boolean preReceive(MessageChannel messageChannel) {
        return false;
    }

    @Override
    public Message<?> postReceive(Message<?> message, MessageChannel messageChannel) {
        return null;
    }

    @Override
    public void afterReceiveCompletion(Message<?> message, MessageChannel messageChannel, Exception e) {
    }
}
